package com.ssyt.yt1.day11.basetype;

class CPU implements Cloneable {

	private String name;

	public CPU() {
		super();
	}

	public CPU(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	protected CPU clone() throws CloneNotSupportedException {
		return (CPU) super.clone();
	}

}

class Computer implements Cloneable {

	private String brand;
	private double price;
	private CPU cpu;

	public Computer() {
		super();
	}

	public Computer(String brand, double price, CPU cpu) {
		super();
		this.brand = brand;
		this.price = price;
		this.cpu = cpu;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public CPU getCpu() {
		return cpu;
	}

	public void setCpu(CPU cpu) {
		this.cpu = cpu;
	}

	@Override
	public Computer clone() throws CloneNotSupportedException {
		Computer computer = (Computer) super.clone();
		// 这里就决定了克隆的对象是独立的！
		computer.setCpu(computer.getCpu().clone());
		return computer;
	}
}

/**
 * 深克隆
 * 
 * @author Administrator
 *
 */
public class ObjectDeepClone {

	/**
	 * 浅克隆：<br/>
	 * 被复制对象的所有变量都含有与原来对象相同的值，而所有的对其他 对象引用仍然指向原来的对象，换言之，浅复制仅仅复制所考虑的对
	 * 象，而不复制它所引用的对象。
	 * 
	 * 
	 * @throws CloneNotSupportedException
	 */
	// public static void testShallowClone() throws CloneNotSupportedException {
	// CPU cpu = new CPU("Core I7");
	//
	// Computer lenovo = new Computer("联想", 9999, cpu);
	// Computer mac = lenovo.clone();
	// mac.getCpu().setName("Core I3");
	//
	// System.out.println(lenovo + "\t" + lenovo.getBrand() + "\t"
	// + lenovo.getPrice() + "\t" + lenovo.getCpu() + "\t"
	// + lenovo.getCpu().getName());
	// System.out.println(mac + "\t" + mac.getBrand() + "\t" + mac.getPrice()
	// + "\t" + mac.getCpu() + "\t" + mac.getCpu().getName());
	// }

	/**
	 * 克隆:<br/>
	 * 深度克隆把要复制的对象所引用的对象都复制了一遍。
	 * 
	 * @throws CloneNotSupportedException
	 */
	public static void testDeepClone() throws CloneNotSupportedException {
		CPU cpu = new CPU("Core I7");

		Computer lenovo = new Computer("联想", 9999, cpu);
		Computer mac = lenovo.clone();
		mac.getCpu().setName("Core I3");

		System.out.println(lenovo + "\t" + lenovo.getBrand() + "\t"
				+ lenovo.getPrice() + "\t" + lenovo.getCpu() + "\t"
				+ lenovo.getCpu().getName());
		System.out.println(mac + "\t" + mac.getBrand() + "\t" + mac.getPrice()
				+ "\t" + mac.getCpu() + "\t" + mac.getCpu().getName());
	}

	public static void main(String[] args) throws CloneNotSupportedException {
		testDeepClone();
	}
}
